package com.atguigu.eduservice.controller;


import com.atguigu.comMonutils.R;
import com.atguigu.eduservice.entity.EduCourse;
import com.atguigu.eduservice.entity.EduCourseDescription;
import com.atguigu.eduservice.entity.dto.CourseInfoDto;
import com.atguigu.eduservice.entity.vo.CourseInfoVO;
import com.atguigu.eduservice.service.EduCourseDescriptionService;
import com.atguigu.eduservice.service.EduCourseService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 处理课程和课程描述 前端控制器
 * course  课程意思
 * </p>
 *
 * @author testjava
 * @since 2024-04-07
 */
@RestController
@RequestMapping("/eduservice/course")
@CrossOrigin
public class EduCourseController {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduCourseDescriptionService eduCourseDescriptionService;

    @PostMapping("addCourseInfo")
    public R addCourse(@RequestBody CourseInfoVO courseInfoVO) {
        String id = eduCourseService.saveCourseInfo(courseInfoVO);
        return R.ok().data("courseId", id);
    }


    /**
     * 数据回显
     * @param courseId
     * @return
     */
    @GetMapping("getCourseInfo")
    public R getCourseInfo(@RequestParam String courseId) {
        CourseInfoDto courseInfoDto = new CourseInfoDto();
        EduCourse courseInfo = eduCourseService.getById(courseId);
        EduCourseDescription courseInfoDescription = eduCourseDescriptionService.getById(courseId);
        BeanUtils.copyProperties(courseInfo, courseInfoDto);
        courseInfoDto.setDescription(courseInfoDescription.getDescription());
        return R.ok().data("courseInfo", courseInfoDto);
    }

    /**
     * 判断这个id是否存在
     * 存在的话存储,不存在的修改.
     *
     * @param courseId
     * @return
     */
    @GetMapping("isExist")
    public R isExist(@RequestParam String courseId) {
        LambdaQueryWrapper<EduCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(EduCourse::getId, courseId);
        EduCourse one = eduCourseService.getOne(lambdaQueryWrapper);
        if (one == null) {
            return R.ok().data("isExist", false);

        }else {
            return R.ok().data("isExist", true);

        }
    }

//    更新课程数据
    @PostMapping("updateCourseInfo")
    public R updateCourseInfo(@RequestBody CourseInfoVO courseInfoVO) {
        EduCourse eduCourse = new EduCourse();
        EduCourseDescription eduCourseDescription = new EduCourseDescription();
        BeanUtils.copyProperties(courseInfoVO, eduCourse);
        BeanUtils.copyProperties(courseInfoVO, eduCourseDescription);

         eduCourseService.updateById(eduCourse);
        eduCourseDescriptionService.updateById(eduCourseDescription);
        return R.ok().data("courseId",eduCourse.getId());
    }



}

